package com.liyu.iblog.dao.jpa;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.liyu.iblog.dao.TagDao;
import com.liyu.iblog.domain.Blog;
import com.liyu.iblog.domain.Tag;

@Repository("tagDao")
public class TagDaoJpa extends GenericDaoJpa<Tag> implements TagDao {

    public static final Logger logger = LoggerFactory.getLogger(TagDaoJpa.class);
    
    public TagDaoJpa() {
        super(Tag.class);
    }

    @Override
    public void updateTagForNewBlog(Blog blog) {
        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            Tag tag = null;
            for(String tagKeyString : blog.getTags()) {
                tag = em.find(Tag.class, tagKeyString);
                if (tag == null) {
                    tag = new Tag();
                    tag.setId(tagKeyString);
                    tag.setName(tagKeyString.replace('-', ' '));
                }
                tag.addBlogKey(blog.getKey());
                em.persist(tag);
            }
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            em.close();
        }
    }
    
    @Override
    public void updateTagForRemovedBlog(Blog blog) {
        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            if (blog.getTags() != null) {
                Tag tag = null;
                for (String keyName : blog.getTags()) {
                    tag = em.find(Tag.class, keyName);
                    if (tag != null) {
                        tag.getBlogKeys().remove(blog.getKey());
                        em.persist(tag);
                    }
                }
            }
            tx.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            em.close();
        }
    }

}
